﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace _6._1
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private async void btnFetch_Click(object sender, EventArgs e)
        {
            string url = txtUrl.Text.Trim();
            if (string.IsNullOrWhiteSpace(url))
            {
                MessageBox.Show("请输入有效的URL地址", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) ||
                (uriResult.Scheme != Uri.UriSchemeHttp && uriResult.Scheme != Uri.UriSchemeHttps))
            {
                MessageBox.Show("请输入有效的HTTP/HTTPS URL", "URL格式错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                // 显示加载状态
                btnFetch.Enabled = false;
                lblStatus.Text = "正在获取内容...";
                progressBar.Visible = true;
                progressBar.Style = ProgressBarStyle.Marquee;

                // 获取网页内容
                string content = await FetchWebContentAsync(url);

                // 解析内容
                ParseContent(content);

                // 显示原始内容
                txtRawContent.Text = content;
                tabControl.SelectedIndex = 0; // 切换到结果标签页

                lblStatus.Text = $"解析完成！找到 {lstPhones.Items.Count} 个手机号，{lstEmails.Items.Count} 个邮箱";
            }
            catch (Exception ex)
            {
                lblStatus.Text = "错误: " + ex.Message;
                MessageBox.Show($"获取内容时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnFetch.Enabled = true;
                progressBar.Visible = false;
            }
        }

        private async Task<string> FetchWebContentAsync(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
                client.Timeout = TimeSpan.FromSeconds(30);

                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();

                return await response.Content.ReadAsStringAsync();
            }
        }

        private void ParseContent(string content)
        {
            // 清空现有结果
            lstPhones.Items.Clear();
            lstEmails.Items.Clear();

            // 匹配手机号码（中国大陆手机号）
            string phonePattern = @"(1[3-9]\d{9})";
            MatchCollection phoneMatches = Regex.Matches(content, phonePattern);
            foreach (Match match in phoneMatches)
            {
                if (!lstPhones.Items.Contains(match.Value))
                {
                    lstPhones.Items.Add(match.Value);
                }
            }

            // 匹配邮箱地址
            string emailPattern = @"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})";
            MatchCollection emailMatches = Regex.Matches(content, emailPattern);
            foreach (Match match in emailMatches)
            {
                if (!lstEmails.Items.Contains(match.Value))
                {
                    lstEmails.Items.Add(match.Value);
                }
            }

            // 如果没有找到结果
            if (lstPhones.Items.Count == 0)
            {
                lstPhones.Items.Add("未找到手机号码");
            }

            if (lstEmails.Items.Count == 0)
            {
                lstEmails.Items.Add("未找到邮箱地址");
            }
        }

        private void btnCopyPhones_Click(object sender, EventArgs e)
        {
            if (lstPhones.Items.Count > 0 && lstPhones.Items[0].ToString() != "未找到手机号码")
            {
                string phones = string.Join(Environment.NewLine, lstPhones.Items);
                Clipboard.SetText(phones);
                lblStatus.Text = "手机号已复制到剪贴板";
            }
        }

        private void btnCopyEmails_Click(object sender, EventArgs e)
        {
            if (lstEmails.Items.Count > 0 && lstEmails.Items[0].ToString() != "未找到邮箱地址")
            {
                string emails = string.Join(Environment.NewLine, lstEmails.Items);
                Clipboard.SetText(emails);
                lblStatus.Text = "邮箱地址已复制到剪贴板";
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            // 添加示例URL
            txtUrl.Text = "https://www.example.com/contact";
            lblStatus.Text = "准备就绪";
        }
    }
}
